import {
  Controller,
  Post,
  UseInterceptors,
  UploadedFile,
  HttpException,
  HttpStatus,
  Get,
  Query
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { UploadService } from './upload.service';
import { getSignedUrl } from '../utils/oss';
import * as fs from 'fs';
import * as path from 'path';

@Controller('upload')
export class UploadController {
  constructor(private readonly uploadService: UploadService) {}

  @Post()
  @UseInterceptors(FileInterceptor('file'))
  async uploadFile(
    @UploadedFile()
    file: Express.Multer.File,
  ) {
    try {
      if (!file) {
        throw new HttpException('没有文件被上传', HttpStatus.BAD_REQUEST);
      }

      // 手动验证文件大小
      const maxSize = 1024 * 1024 * 10; // 10MB
      if (file.size > maxSize) {
        // 删除不符合要求的文件
        if (file.path) {
          try {
            fs.unlinkSync(file.path);
          } catch (unlinkError) {
            console.error('删除无效文件失败:', unlinkError);
          }
        }
        throw new HttpException(
          '文件大小超过限制，最大允许10MB',
          HttpStatus.BAD_REQUEST,
        );
      }

      // 手动验证文件类型
      const allowedTypes = /jpg|jpeg|png|gif/;
      const extName = allowedTypes.test(
        path.extname(file.originalname).toLowerCase(),
      );
      const mimeType = allowedTypes.test(file.mimetype);

      if (!extName || !mimeType) {
        // 删除不符合要求的文件
        if (file.path) {
          try {
            fs.unlinkSync(file.path);
          } catch (unlinkError) {
            console.error('删除无效文件失败:', unlinkError);
          }
        }
        throw new HttpException(
          '文件类型不支持，请上传jpg、jpeg、png或gif格式的图片',
          HttpStatus.BAD_REQUEST,
        );
      }

      return await this.uploadService.uploadFile(file);
    } catch (error) {
      // 如果文件已上传但验证失败，尝试删除
      if (
        file &&
        file.path &&
        error instanceof HttpException &&
        error.getStatus() === HttpStatus.BAD_REQUEST
      ) {
        try {
          fs.unlinkSync(file.path);
        } catch (unlinkError) {
          console.error('删除无效文件失败:', unlinkError);
        }
      }

      // 重新抛出错误，保持原有的错误处理
      if (error instanceof HttpException) {
        throw error;
      }
      throw new HttpException('上传失败', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  // 获取文件的签名URL接口，用于在URL过期后重新获取
  @Get('/getSignedUrl')
  async getSignedUrlForFile(
    @Query('objectName') objectName: string,
    @Query('expires') expires: number = 3600
  ) {
    if (!objectName) {
      throw new HttpException('objectName参数是必需的', HttpStatus.BAD_REQUEST);
    }

    try {
      const signedUrl = await getSignedUrl(objectName, expires);
      return {
        success: true,
        url: signedUrl,
        objectName: objectName,
        expires: expires
      };
    } catch (error) {
      console.error('生成签名URL失败:', error);
      throw new HttpException('生成签名URL失败', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
}
